package com.yicoollxing.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.SocketException;
import java.util.List;

import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FTPUtil {

	private static Logger logger = LoggerFactory.getLogger(FTPUtil.class);

	private static String FTP_IP = PropertiesUtil.getProperty("ftp.server.ip");
	private static String FTP_USER = PropertiesUtil
			.getProperty("ftp.user");
	private static String FTP_PASS = PropertiesUtil
			.getProperty("ftp.pass");

	public FTPUtil(String ip, int port, String user, String pwd) {
		this.FTP_IP = ip;
		this.FTP_PASS = pwd;
		this.FTP_USER = user;
		System.out.print("yicooll"+FTP_IP.trim());
	}

	public static boolean uploadFile(List<File> fileList) throws IOException {
		FTPUtil ftpUtil = new FTPUtil(FTP_IP, 21, FTP_USER, FTP_PASS);
		logger.info("开始连接FTP服务器");
		boolean result=ftpUtil.uploadFile("",fileList);
		logger.info("断开FTP服务器，结果是{}"+result);
		return result;
	}

	private boolean uploadFile(String remotePath, List<File> fileList)
			throws IOException {
		boolean uploaded = true;
		FileInputStream in = null;
		if (connectServer()) {
			try {
				frClient.changeWorkingDirectory(remotePath);
				frClient.setBufferSize(1024);
				frClient.setControlEncoding("UTF-8");
				frClient.setFileType(FTPClient.BINARY_FILE_TYPE);// 二进制类型，防止乱码
				frClient.enterLocalPassiveMode();
				for (File file : fileList) {
					in = new FileInputStream(file);
					frClient.storeFile(file.getName(), in);
				}
			} catch (IOException e) {
				uploaded = false;
				logger.error("上传文件到ftp失败", e);
				e.printStackTrace();
			} finally {
				in.close();
				frClient.disconnect();
			}
		} else {
			uploaded = false;
		}
		return uploaded;
	}

	private boolean connectServer() {

		boolean isSuccess = false;
		frClient = new FTPClient();
		try {
			
			frClient.connect(FTP_IP.trim());
			isSuccess = frClient.login(FTP_USER, FTP_PASS);
		} catch (SocketException e) {
			logger.error("连接FTP服务器错误", e);
		} catch (IOException e) {
			logger.error("连接FTP服务器错误", e);
		}
		return isSuccess;
	}

	private String ip;
	private int port;
	private String user;
	private String pwd;
	private FTPClient frClient;

	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public FTPClient getFrClient() {
		return frClient;
	}

	public void setFrClient(FTPClient frClient) {
		this.frClient = frClient;
	}

}
